package org.example.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.constant.MessageConstant;
import org.example.demo.constant.StatusConstant;
import org.example.demo.entity.*;
import org.example.demo.service.PartyVolunteerService;
import org.example.demo.service.UserService;
import org.example.demo.service.VolunteerDataService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.JWTUtils;
import org.example.demo.util.ReturnMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("party/volunteer")
public class PartyVolunteerController {

    @Resource
    private PartyVolunteerService partyVolunteerService;


    @Resource
    private UserService userService;


    @Autowired
    private VolunteerDataService volunteerDataService;

    // 分页查询入党志愿书列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody PartyVolunteer volunteer,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {


//        ReturnMap returnMap = new ReturnMap();
        Page<PartyVolunteer> page = new Page<>(pageNum, pageSize);

        QueryWrapper<PartyVolunteer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(null != volunteer.getName() && !volunteer.getName().isEmpty(),
                        PartyVolunteer::getName, volunteer.getName())
                .eq(volunteer.getUserId() != null,
                        PartyVolunteer::getUserId, volunteer.getUserId())
                .eq(volunteer.getStatus() != null, PartyVolunteer::getStatus, volunteer.getStatus())
                .orderByDesc(PartyVolunteer::getCreateTime);

        Page<PartyVolunteer> result = partyVolunteerService.page(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();
//        returnMap.setData("page", result);
        map.put("page", result);
        return AjaxResult.success(map);
    }
    // 查询入党志愿书总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody PartyVolunteer partyVolunteer) {


//        ReturnMap returnMap = new ReturnMap();
        QueryWrapper<PartyVolunteer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(null != partyVolunteer.getName() && !partyVolunteer.getName().isEmpty(),
                        PartyVolunteer::getName, partyVolunteer.getName());


        int count = partyVolunteerService.count(queryWrapper);
        Map<String, Object> map = new HashMap<>();
//        returnMap.setData("count", count);
        map.put("count", count);
        return AjaxResult.success(map);
    }
    // 查询入党志愿书详情
    @PostMapping("detail")
    public AjaxResult detail(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();

        PartyVolunteer volunteer = partyVolunteerService.getById(id);

        Map<String, Object> map = new HashMap<>();
//        returnMap.setData("volunteer", volunteer);
        map.put("volunteer", volunteer);
        return AjaxResult.success(map);
    }

    // 提交入党志愿书
    @PostMapping("submit")
    public AjaxResult submit(@RequestBody PartyVolunteer volunteer, HttpServletRequest request) {

//        ReturnMap returnMap = new ReturnMap();
//        if (partyVolunteerService.count(new QueryWrapper<PartyVolunteer>().lambda().eq(PartyVolunteer::getUserId,volunteer.getUserId()))>0){
//            returnMap.setReturnCode(400);
//            return returnMap.getreturnMap();
//        }
        // 获取userId
        String token = request.getHeader("Authorization");
        Integer id = (Integer) JWTUtils.parseToken(token).get("userId");
        volunteer.setUserId(Long.valueOf(id));
        User user=userService.getById(id);
        if (!user.getPoliticalStatus().equals("发展对象")){
//            returnMap.setReturnCode(100);
            return AjaxResult.error("非预备党员,不能提交入党志愿书");
//            return returnMap.getreturnMap();
        }
        if (volunteer.getId() != null) {
            volunteer.setUpdateTime(LocalDateTime.now());
            partyVolunteerService.updateById(volunteer);
        } else {
            volunteer.setCreateTime(LocalDateTime.now());
            volunteer.setUpdateTime(LocalDateTime.now());
            partyVolunteerService.save(volunteer);

            // 插入申请书审核数据
            VolunteerData volunteerData = VolunteerData.builder().
                    volunteerId(volunteer.getId()).
                    status(StatusConstant.PENGING_REVIEW).
                    build();
            volunteerDataService.save(volunteerData);
        }


//        returnMap.setReturnCode(200);
        return AjaxResult.success();
    }


    /**
     * 修改入党志愿书
     *
     * @param partyVolunteer 培训日志信息
     * @return 操作结果
     */
    @PutMapping("update")
    public AjaxResult update(@RequestBody PartyVolunteer partyVolunteer) {
        partyVolunteer.setUpdateTime(LocalDateTime.now());

        if (partyVolunteerService.updateById(partyVolunteer)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error(MessageConstant.INTERNAL_SERVER_ERROR);
        }
    }


    // 获取用户最新入党志愿书
    @GetMapping("latest")
    public AjaxResult getLatestByUser(@RequestParam Integer userId) {

//        ReturnMap returnMap = new ReturnMap();
        QueryWrapper<PartyVolunteer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PartyVolunteer::getUserId, userId)
                .orderByDesc(PartyVolunteer::getCreateTime)
                .last("LIMIT 1");

        PartyVolunteer volunteer = partyVolunteerService.getOne(queryWrapper);

        Map<String, Object> map = new HashMap<>();
//        returnMap.setData("volunteer", volunteer);
        map.put("volunteer", volunteer);
        return AjaxResult.success(map);
    }

    // 删除入党志愿书
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Long id) {
//        ReturnMap returnMap = new ReturnMap();
        boolean success = partyVolunteerService.removeById(id);

        if (success) {
            volunteerDataService.deleteByVolunteerId(id);
            return AjaxResult.success();
        }
        return AjaxResult.error();

    }


    @GetMapping("/select")
    public AjaxResult getById(@RequestParam("id") Long id) {

        Map<String, Object> map = new HashMap<>();
        map.put("user_id", id);

        List<PartyVolunteer> partyVolunteers = partyVolunteerService.listByMap(map);

        Map<String, Object> maps = new HashMap<>();
        maps.put("partyVolunteers", partyVolunteers);
        return AjaxResult.success(maps);
    }
}
